﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Xrm.Framework.Test.Integration;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.Linq;
using Microsoft.Xrm.Sdk;
using System.Collections.Generic;

namespace IntegrationTests
{
    [TestClass]
    public class TestPreAccountCreate : PluginIntegrationTest
    {
        #region Instance Variables

        private Guid entityId = Guid.NewGuid();

        #endregion

        [TestMethod]
        public void TestAccountAutoNumberIsGenerated()
        {
            base.Test();
        }

        protected override Microsoft.Xrm.Sdk.OrganizationRequest SetupTriggerRequest()
        {
            Entity entity = new Entity("account");
            entity.Id = entityId;
            entity["name"] = "Wael " + DateTime.Now.ToString();

            CreateRequest request = new CreateRequest();
            request.Target = entity;

            return request;
        }

        protected override void Verify()
        {
            QueryByAttribute query = new QueryByAttribute()
            {
                ColumnSet = new ColumnSet(true),
                EntityName = "xdft_configuration",
                Attributes = { "xdft_name" },
                Values = { "AutoNumberPrefix" }
            };

            EntityCollection entities = base.OrganizationService.RetrieveMultiple(query);

            if (entities.Entities.Count != 1)
            {
                throw new InvalidPluginExecutionException(string.Format("Config Match Count not 1 {0}", entities.Entities.Count));
            }

            string prefix = entities.Entities[0]["xdft_value"].ToString();

            Entity entity = base.OrganizationService.Retrieve("account", entityId, new ColumnSet(true));

            Assert.IsTrue(entity["xdft_reference"].ToString().StartsWith(prefix));
        }

        protected override void CleanUp()
        {
            base.CleanUp();

            base.OrganizationService.Delete("account", entityId);
        }
    }
}
